package service

import (
	"singo/model"
	"singo/serializer"

	uuid "github.com/satori/go.uuid"
	// "github.com/segmentio/ksuid"
	// "github.com/rs/xid"
)

// UserRegisterService 管理用户注册服务
type UserRegisterService struct {
	Nickname        string `form:"nickname" json:"nickname" binding:"required"`
	UserName        string `form:"username" json:"username" binding:"required,min=2,max=30"`
	Password        string `form:"password" json:"password" binding:"required,min=6,max=40"`
	PasswordConfirm string `form:"password_confirm" json:"password_confirm" binding:"required,min=6,max=40"`
	UserType        int    `form:"user_type" json:"user_type" binding:"required"`
	Gender          int    `form:"gender" json:"gender"`
	OrganizationID  string `form:"organization_id" json:"organization_id"`
	Job             string `form:"job" json:"job"`
	Rank            int    `form:"rank" json:"rank" binding:"required"`
	Level           int    `form:"level" json:"level"`
}

// valid 验证表单
func (service *UserRegisterService) valid() *serializer.Response {
	if service.PasswordConfirm != service.Password {
		return &serializer.Response{
			Status: 40001,
			Msg:    "两次输入的密码不相同",
		}
	}

	count := 0
	model.DB.Model(&model.User{}).Where("user_name = ?", service.UserName).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Status: 40001,
			Msg:    "邮箱已经注册",
		}
	}

	return nil
}

// Register 用户注册
func (service *UserRegisterService) Register() serializer.Response {
	uid := uuid.NewV4()
	// uid := ksuid.New()
	// uid := xid.New()

	// 表单验证
	if err := service.valid(); err != nil {
		return *err
	}

	user := model.User{
		UID:             uid.String(),
		UserName:        service.UserName,
		Nickname:        service.Nickname,
		Password:        service.Password,
		UserType:        service.UserType,
		OrganizationUID: service.OrganizationID,
		Gender:          service.Gender, // 性别 1男2女0未知
		Job:             service.Job,
		Rank:            service.Rank,
		Level:           service.Level,
	}

	// 加密密码
	if err := user.SetPassword(service.Password); err != nil {
		return serializer.Err(
			serializer.CodeEncryptError,
			"密码加密失败",
			err,
		)
	}

	// 创建用户
	if err := model.DB.Create(&user).Error; err != nil {
		return serializer.ParamErr("注册失败", err)
	}

	return serializer.BuildUserResponse(user)
}
